#include "defines.h"


/// get value in ruple by order
/// Example: get_value(tuple_s, 0) -> value C of tuple s
/// Example: get_value(tuple_s, 1) -> value D of tuple s
int get_value(unsigned char tuple[8], int order){
    unsigned char str[5];
    str[5] = '\0';
    for (int k = 0; k < 4; k++)
    {
        str[k] = tuple[order*4 + k];
    }
    return atoi(str);
}

void turple_cpy(unsigned char str_to[8], unsigned char str_from[8]){
    for(int i=0; i<8; i++)
        str_to[i] = str_from[i];
}

// return 1 if equal
int is_turple_equal(unsigned char str_to[8], unsigned char str_from[8]){
    for(int i=0; i<BYTES_TUPLE; i++){
        if(str_to[i] != str_from[i])
            return 0;
    }
    return 1;
}

void clear_tuple(unsigned char tuple[8]){
    for(int i=0; i<8; i++)
        tuple[i] = 0;
}

void clear_buffer(unsigned char* buffer){
    for(int i=0; i<BYTES_BLK; i++)
        buffer[i] = 0;
}

void itoa(unsigned char str[4], int value){
    int num[4];
    int i=0;
    for(i=0; i<4; i++){
        num[i] = value%10;
        value /= 10;
        if(value == 0)
            break;
    }
    for(int j=0; j<=i; j++){
        str[j] = num[i-j] + '0';
    }
    for(int j=i+1; j<4; j++){
        str[j] = 0;
    }
}

/// Warning: this func is only used to compare value
///         S.A or R.C (two bytes)
int is_leq(unsigned char value1[3], unsigned char value2[3]){
    // printf("(value1:%d,value2:%d,leq:%d)",atoi(value1), atoi(value2),atoi(value1) <= atoi(value2));
    return (atoi(value1) <= atoi(value2));
}

void print_tuple(unsigned char tuple[8]){
    unsigned char str[9];
    for(int i=0; i<BYTES_TUPLE; i++)
        str[i] = tuple[i];
    printf("(%d,%d)",atoi(str),atoi(str+BYTES_TUPLE/2));
}

void print_blk(unsigned char blk[64]){
    printf("block: ");
    for(int i=0; i<MAX_TUPLE_PBLK+1; i++)
        printf("%d,",atoi(blk+BYTES_TUPLE*i));
    printf("\n");
}



// No copy of "next blk num pointer"(tuple 8)
void blk_copy(unsigned char blk_to[64], unsigned char blk_from[64]){
    for(int i=0; i<MAX_TUPLE_PBLK; i++)
        turple_cpy(get_turple_addr(i,blk_to), get_turple_addr(i,blk_from));
}